package com.zmn.plat.admin.controller.orderconfig.distribute;

import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.common.dictionary.DistributeWayEnum;
import com.zmn.plat.common.dictionary.PlatEnum;
import com.zmn.plat.common.dto.orderconfig.distribute.RobOrderDIO;
import com.zmn.plat.model.entity.orderconfig.distribute.*;
import com.zmn.plat.services.interfaces.orderconfig.distribute.RobOrderConfigService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.dubbo.constant.DistributeConsts;
import com.zmn.plat.model.vo.company.BaseCompanyVO;

/**
 * 类描述：派单参数配置修改控制器
 *
 * @author mujunlin
 * @version v1.0
 * @since 2019/10/17 20:14
 */
@RestController
@RequestMapping("/orderconfig/distribute/")
public class DistributeWeightModifyController extends DistributeWeightBaseController {

    private Logger logger = LoggerFactory.getLogger(DistributeWeightModifyController.class);

    private static final String ROB_ORDER = "robOrder";

    private static final String SEND_ORDER = "sendOrder";

    @Resource
    private RobOrderConfigService robOrderConfigService;

    /**
     * 修改平台派单参数配置信息
     *
     * @param request HttpServletRequest
     * @param vo      平台派单参数
     * @return 操作结果
     */
    @RequestMapping("plat/modifyOrInsert")
    public ResponseDTO platModify(HttpServletRequest request, @RequestBody DistributeWeightPlat vo) {

        try {
            if (Objects.isNull(vo)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }
            if (NumberUtil.isNullOrZero(vo.getDistributePlatId())) {
                //判断是平台派单还是服务商派单
                int data = 0;
                if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&& DistributeWayEnum.DISTRIBUTE_WAY_PLAT.getCode().equals(vo.getDistributeWay())) {
                    data = vo.getCityId();
                }
                if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&&DistributeWayEnum.DISTRIBUTE_WAY_SP.getCode().equals(vo.getDistributeWay())) {
                    data = vo.getPlat();
                }
                //从redis获取派单信息
                String redisData = robOrderConfigBService.getDataFromRedis(SEND_ORDER, data);
                if (StringUtils.isBlank(redisData)) {
                    return ResponseDTO.fail("请先设置对应的派单规则！");
                }
                DistributeWeightPlat newVO = JSONObject.parseObject(redisData, DistributeWeightPlat.class);
                newVO.setAutoStatusRework(vo.getAutoStatusRework());
                newVO.setReworkLimit(vo.getReworkLimit());
                // 新单简单派单，默认为：启用（数据同步为：启用）
                if (Objects.isNull(newVO.getNewSimpleStatus())) {
                    newVO.setNewSimpleStatus(GlobalConsts.NO);
                }
                // 新单自动派单，默认为：公平自动派
                if (Objects.isNull(newVO.getAutoStatusNew())) {
                    newVO.setAutoStatusNew(DistributeConsts.AUTO_STATUS_FAIR);
                }
                // 返修自动派单，默认为：源工程师自动派
                if (Objects.isNull(newVO.getAutoStatusRework())) {
                    newVO.setAutoStatusRework(DistributeConsts.REWORK_STATUS_ENGINEER);
                }
                if (StringUtils.isNotBlank(newVO.getAutoTimeStr())) {
                    String timeStr = newVO.getAutoTimeStr();
                    String[] timeStrArray = timeStr.split(" ~ ");
                    newVO.setAutoTimeStart(timeStrArray[0]);
                    newVO.setAutoTimeEnd(timeStrArray[1]);
                }
                String userName = super.getMcStaffRealName();
                newVO.setUpdater(userName);
                newVO.setUpdateTime(DateUtil.getNow());
                // 新增
                newVO.setStatus(GlobalConsts.YES);
                newVO.setCreater(userName);
                newVO.setCreateTime(DateUtil.getNow());
                distributeWeightPlatBService.insert(newVO);
                newVO.getDistributeWeightRelationList().forEach(r -> {
                    r.setDistributeConfigId(newVO.getDistributePlatId());
                    r.setCreater(userName);
                    r.setCreateTime(DateUtil.getNow());
                    r.setUpdater(userName);
                    r.setUpdateTime(DateUtil.getNow());
                });
                distributeWeightRelationService.insertBatch(newVO.getDistributeWeightRelationList());
                //新增成功删除redis缓存
                robOrderConfigBService.delDataFromRedis(SEND_ORDER, data);
            } else {
                // 新单简单派单，默认为：启用（数据同步为：启用）
                if (Objects.isNull(vo.getNewSimpleStatus())) {
                    vo.setNewSimpleStatus(GlobalConsts.NO);
                }
                // 新单自动派单，默认为：公平自动派
                if (Objects.isNull(vo.getAutoStatusNew())) {
                    vo.setAutoStatusNew(DistributeConsts.AUTO_STATUS_FAIR);
                }
                // 返修自动派单，默认为：源工程师自动派
                if (Objects.isNull(vo.getAutoStatusRework())) {
                    vo.setAutoStatusRework(DistributeConsts.REWORK_STATUS_ENGINEER);
                }
                if (StringUtils.isNotBlank(vo.getAutoTimeStr())) {
                    String timeStr = vo.getAutoTimeStr();
                    String[] timeStrArray = timeStr.split(" ~ ");
                    vo.setAutoTimeStart(timeStrArray[0]);
                    vo.setAutoTimeEnd(timeStrArray[1]);
                }
                String userName = super.getMcStaffRealName();
                vo.setUpdater(userName);
                vo.setUpdateTime(DateUtil.getNow());
                distributeWeightPlatBService.updateByKey(vo);
                if (CollectionUtil.isNotNullOrEmpty(vo.getDistributeWeightRelationList())) {
                    vo.getDistributeWeightRelationList().forEach(r -> {
                        r.setUpdater(userName);
                        r.setUpdateTime(DateUtil.getNow());
                        if (r.getRelationId() == null) {
                            r.setDistributeConfigId(vo.getDistributePlatId());
                            r.setCreater(userName);
                            r.setCreateTime(DateUtil.getNow());
                            distributeWeightRelationService.insert(r);
                        } else {
                            distributeWeightRelationService.updateByKey(r);
                        }
                    });
                }

            }
            return ResponseDTO.success(true, "修改平台派单参数成功！");
        } catch (Exception ex) {
            logger.error("修改平台派单参数失败,vo:{},ex:{}", vo, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }
    }

    /**
     * 平台配置状态修改
     *
     * @param request HttpServletRequest
     * @param query   状态修改查询对象
     * @return 操作结果
     */
    @RequestMapping("plat/status/modify")
    public ResponseDTO platStatusModify(HttpServletRequest request, DistributeWeightStatusQuery query) {

        try {
            if (Objects.isNull(query)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }

            String userName = super.getMcStaffRealName();
            query.setUpdater(userName);
            query.setUpdateTime(DateUtil.getNow());
            distributeWeightPlatBService.updateStatusByQuery(query);

            return ResponseDTO.success(true, "修改平台派单参数状态成功！");
        } catch (Exception ex) {
            logger.error("修改平台派单参数状态失败,query:{},ex:{}", query, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }

    }

    /**
     * 修改公司派单参数配置信息
     *
     * @param request HttpServletRequest
     * @param vo      公司派单参数
     * @return 操作结果
     */
    @RequestMapping("company/modify")
    public ResponseDTO companyModify(HttpServletRequest request, @RequestBody DistributeWeightCompany vo) {

        try {

            if (Objects.isNull(vo)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }
            if (Objects.isNull(vo.getWeightId())) {
                int data = 0;
                //companyId有值说明是服务商抢单设置
                if(NumberUtil.isNotNullOrZero(vo.getCompanyId())){
                    data = vo.getCompanyId()+vo.getCityId();
                }
                //从redis获取派单信息
                String redisData = robOrderConfigBService.getDataFromRedis(SEND_ORDER, data);
                DistributeWeightCompany newVO = JSONObject.parseObject(redisData, DistributeWeightCompany.class);
                newVO.setAutoStatusRework(vo.getAutoStatusRework());
                newVO.setReworkLimit(vo.getReworkLimit());
                // 新单简单派单，默认为：启用（数据同步为：启用）
                if (Objects.isNull(newVO.getNewSimpleStatus()) && Objects.equals(newVO.getBizType(), ProductConsts.BIZ_TYPE_C)) {
                    newVO.setNewSimpleStatus(GlobalConsts.NO);
                }
                // 新单自动派单，默认为：公平自动派
                if (Objects.isNull(newVO.getAutoStatusNew())) {
                    newVO.setAutoStatusNew(DistributeConsts.AUTO_STATUS_FAIR);
                }
                // 返修自动派单，默认为：源工程师自动派
                if (Objects.isNull(newVO.getAutoStatusRework())) {
                    newVO.setAutoStatusRework(DistributeConsts.REWORK_STATUS_ENGINEER);
                }
                // 设置自动派单时间
                if (StringUtils.isNotBlank(newVO.getAutoTimeStr())) {
                    String timeStr = newVO.getAutoTimeStr();
                    String[] timeStrArray = timeStr.split(" ~ ");
                    newVO.setAutoTimeStart(timeStrArray[0]);
                    newVO.setAutoTimeEnd(timeStrArray[1]);
                }
                // 新增配置时，通过服务商ID查询所归属的子公司
                if (NumberUtil.isNullOrZero(newVO.getSubCompanyId())) {
                    Integer companyId = newVO.getCompanyId();
                    BaseCompanyVO spCompany = baseCompanyService.findByKey(companyId);
                    if (Objects.isNull(spCompany) || Objects.isNull(spCompany.getSubCompanyId())) {
                        newVO.setSubCompanyId(GlobalConsts.NONE);
                    } else {
                        newVO.setSubCompanyId(spCompany.getSubCompanyId());
                    }
                }
                String userName = super.getMcStaffRealName();
                newVO.setUpdater(userName);
                newVO.setUpdateTime(DateUtil.getNow());
                if (Objects.isNull(newVO.getWeightId())) {
                    newVO.setCreater(userName);
                    newVO.setCreateTime(DateUtil.getNow());
                }
                if (StringUtils.isBlank(redisData)) {
                    return ResponseDTO.fail("请先设置对应的派单规则！");
                }
                if (checkExistsByCompanyAndCityId(vo.getPlat(), vo.getCompanyId(), vo.getCityId(), vo.getBizType())) {
                    return ResponseDTO.fail("服务商在该区域配置信息已存在，请勿重复添加！");
                }
                distributeWeightCompanyService.insert(newVO);
                newVO.getDistributeWeightRelationList().forEach(r -> {
                    r.setDistributeConfigId(newVO.getWeightId());
                    r.setCreater(userName);
                    r.setCreateTime(DateUtil.getNow());
                    r.setUpdater(userName);
                    r.setUpdateTime(DateUtil.getNow());
                });
                distributeWeightRelationService.insertBatch(newVO.getDistributeWeightRelationList());
                //新增成功删除redis缓存
                 robOrderConfigBService.delDataFromRedis(SEND_ORDER, data);
            } else {
                // 新单简单派单，默认为：启用（数据同步为：启用）
                if (Objects.isNull(vo.getNewSimpleStatus()) && Objects.equals(vo.getBizType(), ProductConsts.BIZ_TYPE_C)) {
                    vo.setNewSimpleStatus(GlobalConsts.NO);
                }
                // 新单自动派单，默认为：公平自动派
                if (Objects.isNull(vo.getAutoStatusNew())) {
                    vo.setAutoStatusNew(DistributeConsts.AUTO_STATUS_FAIR);
                }
                // 返修自动派单，默认为：源工程师自动派
                if (Objects.isNull(vo.getAutoStatusRework())) {
                    vo.setAutoStatusRework(DistributeConsts.REWORK_STATUS_ENGINEER);
                }
                // 设置自动派单时间
                if (StringUtils.isNotBlank(vo.getAutoTimeStr())) {
                    String timeStr = vo.getAutoTimeStr();
                    String[] timeStrArray = timeStr.split(" ~ ");
                    vo.setAutoTimeStart(timeStrArray[0]);
                    vo.setAutoTimeEnd(timeStrArray[1]);
                }
                // 新增配置时，通过服务商ID查询所归属的子公司
                if (NumberUtil.isNullOrZero(vo.getSubCompanyId())) {
                    Integer companyId = vo.getCompanyId();
                    BaseCompanyVO spCompany = baseCompanyService.findByKey(companyId);
                    if (Objects.isNull(spCompany) || Objects.isNull(spCompany.getSubCompanyId())) {
                        vo.setSubCompanyId(GlobalConsts.NONE);
                    } else {
                        vo.setSubCompanyId(spCompany.getSubCompanyId());
                    }
                }
                String userName = super.getMcStaffRealName();
                vo.setUpdater(userName);
                vo.setUpdateTime(DateUtil.getNow());
                if (Objects.isNull(vo.getWeightId())) {
                    vo.setCreater(userName);
                    vo.setCreateTime(DateUtil.getNow());
                }
                distributeWeightCompanyService.updateByKey(vo);
                vo.getDistributeWeightRelationList().forEach(r -> {
                    r.setUpdater(userName);
                    r.setUpdateTime(DateUtil.getNow());
                    if (r.getRelationId() == null) {
                        r.setDistributeConfigId(vo.getWeightId());
                        r.setCreater(userName);
                        r.setCreateTime(DateUtil.getNow());
                        distributeWeightRelationService.insert(r);
                    } else {
                        distributeWeightRelationService.updateByKey(r);
                    }
                });
            }
            return ResponseDTO.success(true, "新增/修改服务商派单参数成功！");
        } catch (Exception ex) {
            logger.error("新增/修改服务商派单参数失败,vo:{},ex:{}", vo, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }
    }

    /**
     * 公司配置状态修改
     *
     * @param request HttpServletRequest
     * @param query   状态修改查询对象
     * @return 操作结果
     */
    @RequestMapping("company/status/modify")
    public ResponseDTO companyStatusModify(HttpServletRequest request, DistributeWeightStatusQuery query) {

        try {
            if (Objects.isNull(query)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }

            String userName = super.getMcStaffRealName();
            query.setUpdater(userName);
            query.setUpdateTime(DateUtil.getNow());
            distributeWeightCompanyService.updateStatusByQuery(query);

            return ResponseDTO.success(true, "修改公司派单参数状态成功！");
        } catch (Exception ex) {
            logger.error("修改公司派单参数状态失败,query:{},ex:{}", query, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }

    }

    /**
     * 修改平台抢单参数配置信息
     *
     * @param request HttpServletRequest
     * @param vo      平台抢单参数
     * @return 操作结果
     */
    @RequestMapping("plat/robOrder/modifyOrInsert")
    public ResponseDTO platRobOrderModify(HttpServletRequest request, @RequestBody RobOrderConfigInfo vo) {
        try {
            if (Objects.isNull(vo)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }
            String userName = super.getMcStaffRealName();
            vo.setUpdater(userName);
            vo.setUpdateTime(DateUtil.getNow());
            if (NumberUtil.isNullOrZero(vo.getConfigId())) {
                //判断当前城市是否已有规则存在;
                if (NumberUtil.isNullOrZero(vo.getCompanyId())&&
                        checkExistsByCityId(vo.getCityId(), vo.getPlat(), vo.getDistributeWay(),vo.getCompanyId(),vo.getBizType())) {
                    return ResponseDTO.fail("该区域配置信息已存在，请勿重复添加！");
                };
                if (NumberUtil.isNotNullOrZero(vo.getCompanyId())&&
                        checkExistsByCityId(vo.getCityId(), vo.getPlat(), vo.getDistributeWay(),vo.getCompanyId(),vo.getBizType())) {
                    return ResponseDTO.fail("服务商在该区域配置信息已存在，请勿重复添加！");
                };
                //判断是平台派单还是服务商派单
                int data = 0;
                if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&&DistributeWayEnum.DISTRIBUTE_WAY_PLAT.getCode().equals(vo.getDistributeWay())) {
                    data = vo.getCityId();
                }
                if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&&DistributeWayEnum.DISTRIBUTE_WAY_SP.getCode().equals(vo.getDistributeWay())) {
                    data = vo.getPlat();
                }
                //companyId有值说明是服务商抢单设置
                if(NumberUtil.isNotNullOrZero(vo.getCompanyId())){
                    data = vo.getCompanyId()+vo.getCityId();
                }

                //从redis获取抢单信息
                String redisData = robOrderConfigBService.getDataFromRedis(ROB_ORDER, data);
                if (StringUtils.isBlank(redisData)) {
                    if(NumberUtil.isNotNullOrZero(vo.getCompanyId())){
                        return ResponseDTO.fail("请先设置该服务商的抢单规则！");
                    }else{
                        return ResponseDTO.fail("请先设置" + vo.getCityName() + "的抢单规则！");
                    }

                }
                vo = JSONObject.parseObject(redisData, RobOrderConfigInfo.class);
                if (Objects.isNull(vo.getRobOrderStatus()) ) {
                    vo.setRobOrderStatus(GlobalConsts.NO);
                }
                vo.setCreater(userName);
                vo.setCreateTime(DateUtil.getNow());
                vo.setPlat(PlatEnum.ZMN.value);
                robOrderConfigBService.insert(vo);
                int configId = vo.getConfigId();
                if (!CollectionUtil.isNullOrEmpty(vo.getRobOrderRelationList())) {
                    List<RobOrderRelation> robOrderRelationList = vo.getRobOrderRelationList();
                    robOrderRelationList.forEach(r -> {
                        //预约时间
                        if (StringUtils.isNotBlank(r.getAppointmentTimeStr())) {
                            String appointmentTimeStr = r.getAppointmentTimeStr();
                            String[] appointmentTimeArr = appointmentTimeStr.split(" ~ ");
                            r.setAppointmentTimeStart(appointmentTimeArr[0]);
                            r.setAppointmentTimeEnd(appointmentTimeArr[1]);
                        }
                        //下单时间
                        if (StringUtils.isNotBlank(r.getOrderTimeStr())) {
                            String orderTimeStr = r.getOrderTimeStr();
                            String[] orderTimeArr = orderTimeStr.split(" ~ ");
                            r.setOrderTimeStart(orderTimeArr[0]);
                            r.setOrderTimeEnd(orderTimeArr[1]);
                        }
                        //抢单时间
                        if (StringUtils.isNotBlank(r.getRobOrderTimeStr())) {
                            String robOrderTimeStr = r.getRobOrderTimeStr();
                            String[] robOrderTimeArr = robOrderTimeStr.split(" ~ ");
                            r.setRobOrderTimeStart(robOrderTimeArr[0]);
                            r.setRobOrderTimeEnd(robOrderTimeArr[1]);
                        }
                        r.setConfigId(configId);
                        r.setCreater(userName);
                        r.setCreateTime(DateUtil.getNow());
                        r.setUpdater(userName);
                        r.setUpdateTime(DateUtil.getNow());
                        robOrderConfigBService.insertRelationData(r);
                        int relationId = r.getRelationId();
                        List<RobOrderRelationProduct> robOrderRelationProductList = r.getRobOrderRelationProductList();
                        if (!CollectionUtil.isNullOrEmpty(robOrderRelationProductList)) {
                            robOrderRelationProductList.forEach(item -> {
                                item.setRelationId(relationId);
                                item.setCreater(userName);
                                item.setCreateTime(DateUtil.getNow());
                                item.setUpdater(userName);
                                item.setUpdateTime(DateUtil.getNow());
                            });
                        }
                        robOrderConfigBService.insertBatchProduct(robOrderRelationProductList);
                    });
                }
                //删除redis数据缓存
                robOrderConfigBService.delDataFromRedis(ROB_ORDER, data);
            } else {
                robOrderConfigBService.updateByKey(vo);
                Integer configId = vo.getConfigId();
                //删除关联表数据，再新增
                robOrderConfigBService.deleteByConfigId(configId);
                if (!CollectionUtil.isNullOrEmpty(vo.getRobOrderRelationList())) {
                    vo.getRobOrderRelationList().forEach(r -> {
//                        int relationId = r.getRelationId();
                        if(NumberUtil.isNotNullOrZero(r.getRelationId())){
                            //删除关联产品表数据，再新增
                            robOrderConfigBService.deleteByRelationId(r.getRelationId());
                        }

                        //预约时间
                        if (StringUtils.isNotBlank(r.getAppointmentTimeStr())) {
                            String appointmentTimeStr = r.getAppointmentTimeStr();
                            String[] appointmentTimeArr = appointmentTimeStr.split(" ~ ");
                            r.setAppointmentTimeStart(appointmentTimeArr[0]);
                            r.setAppointmentTimeEnd(appointmentTimeArr[1]);
                        }
                        //下单时间
                        if (StringUtils.isNotBlank(r.getOrderTimeStr())) {
                            String orderTimeStr = r.getOrderTimeStr();
                            String[] orderTimeArr = orderTimeStr.split(" ~ ");
                            r.setOrderTimeStart(orderTimeArr[0]);
                            r.setOrderTimeEnd(orderTimeArr[1]);
                        }
                        //抢单时间
                        if (StringUtils.isNotBlank(r.getRobOrderTimeStr())) {
                            String robOrderTimeStr = r.getRobOrderTimeStr();
                            String[] robOrderTimeArr = robOrderTimeStr.split(" ~ ");
                            r.setRobOrderTimeStart(robOrderTimeArr[0]);
                            r.setRobOrderTimeEnd(robOrderTimeArr[1]);
                        }
                        r.setConfigId(configId);
                        //前端传入的主键置空
                        r.setRelationId(null);
                        r.setCreater(userName);
                        r.setCreateTime(DateUtil.getNow());
                        r.setUpdater(userName);
                        r.setUpdateTime(DateUtil.getNow());
                        robOrderConfigBService.insertRelationData(r);
                        Integer newRelationId = r.getRelationId();
                        List<RobOrderRelationProduct> robOrderRelationProductList = r.getRobOrderRelationProductList();
                        if (!CollectionUtil.isNullOrEmpty(robOrderRelationProductList)) {
                            robOrderRelationProductList.forEach(item -> {
                                item.setRelationProductId(null);
                                item.setRelationId(newRelationId);
                                item.setCreater(userName);
                                item.setCreateTime(DateUtil.getNow());
                                item.setUpdater(userName);
                                item.setUpdateTime(DateUtil.getNow());
                            });
                        }
                        robOrderConfigBService.insertBatchProduct(r.getRobOrderRelationProductList());
                    });

                }
                //更新操作删除redis配置数据
                String redisKey = vo.getCityId()+":"+vo.getCompanyId();
                redisManager.del("plat:orderConfig:robOrderConfig"+":"+redisKey);
            }
            return ResponseDTO.success(true, "修改平台派单参数成功！");
        } catch (Exception ex) {
            logger.error("修改平台派单参数失败,vo:{},ex:{}", vo, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }
    }


    @RequestMapping(value = "updateRobOrderStatus", method = RequestMethod.POST)
    public ResponseDTO updateStatus(@RequestParam(value = "idList", defaultValue = "") String idList,
                                    @RequestParam(value = "status", defaultValue = "") Integer status) {
        try {
            UpdateStatusQuery updateStatusQuery =UpdateStatusQuery.builder()
                    .status(status)
                    .idList(StringUtil.convertStrsToList(idList))
                    .build();
            robOrderConfigBService.updateStatus(updateStatusQuery);
            //删除缓存
            List<RobOrderConfigInfo> configList = robOrderConfigService.listConfigInfoByConfigIds(StringUtil.convertStrsToList(idList));
            if(!CollectionUtils.isEmpty(configList)){
                configList.forEach(e ->{
                    redisManager.del("plat:orderConfig:robOrderConfig"+":"+e.getCityId()+":"+e.getCompanyId());
                });
            }
            return ResponseDTO.success(true, "状态修改成功！");
        } catch (
                Exception ex) {
            logger.error("状态修改失败,vo:{},ex:{}", ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }

    }


    /**
     * @param request HttpServletRequest
     * @param vo      平台抢单参数
     * @return 操作结果
     */
    @RequestMapping("plat/setRobOrderConfigDataToRedis")
    public ResponseDTO setOrderConfigDataToRedis(HttpServletRequest request, @RequestBody RobOrderConfigInfo vo) {
        try {
            if (Objects.isNull(vo)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }
            //判断当前城市是否已有规则存在;
            if (NumberUtil.isNullOrZero(vo.getCompanyId())
                    &&NumberUtil.isNotNullOrZero(vo.getCityId())
                    &&checkExistsByCityId(vo.getCityId(), vo.getPlat(), vo.getDistributeWay(),vo.getCompanyId(),vo.getBizType())) {
                return ResponseDTO.fail("该区域配置信息已存在，请勿重复添加！");
            };
            //判断当前服务平台是否已有规则存在;
            if (NumberUtil.isNullOrZero(vo.getCompanyId())
                    &&NumberUtil.isNullOrZero(vo.getCityId())
                    &&checkExistsByCityId(vo.getCityId(), vo.getPlat(), vo.getDistributeWay(),vo.getCompanyId(),vo.getBizType())) {
                return ResponseDTO.fail("该服务平台配置信息已存在，请勿重复添加！");
            };
            //判断当前服务商是否已有规则存在;
            if (NumberUtil.isNotNullOrZero(vo.getCompanyId())&&
                    checkExistsByCityId(vo.getCityId(), vo.getPlat(), vo.getDistributeWay(),vo.getCompanyId(),vo.getBizType())) {
                return ResponseDTO.fail("服务商在该区域配置信息已存在，请勿重复添加！");
            };
            //判断是平台派单还是服务商派单
            int data = 0;
            if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&&DistributeWayEnum.DISTRIBUTE_WAY_PLAT.getCode().equals(vo.getDistributeWay())) {
                data = vo.getCityId();
            }
            if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&&DistributeWayEnum.DISTRIBUTE_WAY_SP.getCode().equals(vo.getDistributeWay())) {
                data = vo.getPlat();
            }
            if(NumberUtil.isNotNullOrZero(vo.getCompanyId())){
                data = vo.getCompanyId()+vo.getCityId();
            }

            robOrderConfigBService.setDataToRedis(ROB_ORDER, data, JSONObject.toJSONString(vo));
            return ResponseDTO.success(true, "数据缓存成功！");
        } catch (Exception ex) {
            logger.error("数据缓存失败,vo:{},ex:{}", vo, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }
    }

    /**
     * @param request HttpServletRequest
     * @param vo      平台派单参数
     * @return 操作结果
     */
    @RequestMapping("plat/setSendOrderConfigDataToRedis")
    public ResponseDTO setOrderConfigDataToRedis(HttpServletRequest request, @RequestBody DistributeWeightPlat vo) {
        try {
            if (Objects.isNull(vo)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }
            //判断是平台派单还是服务商派单
            int data = 0;
            if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&&DistributeWayEnum.DISTRIBUTE_WAY_PLAT.getCode().equals(vo.getDistributeWay())) {
                data = vo.getCityId();
            }
            if (NumberUtil.isNotNullOrZero(vo.getDistributeWay())&&DistributeWayEnum.DISTRIBUTE_WAY_SP.getCode().equals(vo.getDistributeWay())) {
                data = vo.getPlat();
            }

            //判断是否设置了抢单条件设置
            if (StringUtils.isBlank(robOrderConfigBService.getDataFromRedis(ROB_ORDER, data))) {
                return ResponseDTO.fail("请先设置" + vo.getCityName() + "的抢单规则！");
            }
            robOrderConfigBService.setDataToRedis(SEND_ORDER, data, JSONObject.toJSONString(vo));
            return ResponseDTO.success(true, "数据缓存成功！");
        } catch (Exception ex) {
            logger.error("数据缓存失败,vo:{},ex:{}", vo, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }
    }

    /**
     * @param request HttpServletRequest
     * @param vo      服务商派单参数
     * @return 操作结果
     */
    @RequestMapping("plat/setCompanySendOrderConfigDataToRedis")
    public ResponseDTO setCompanySendOrderConfigDataToRedis(HttpServletRequest request, @RequestBody DistributeWeightCompany vo) {
        try {
            if (Objects.isNull(vo)) {
                return ResponseDTO.fail("保存参数不能为空！");
            }
            //判断是平台派单还是服务商派单
            int data = 0;
            if(NumberUtil.isNotNullOrZero(vo.getCompanyId())){
                data = vo.getCompanyId()+vo.getCityId();
            }
            //判断是否设置了抢单条件设置
            if (StringUtils.isBlank(robOrderConfigBService.getDataFromRedis(ROB_ORDER, data))) {
                return ResponseDTO.fail("请先设置对应服务商的抢单规则！");
            }
            robOrderConfigBService.setDataToRedis(SEND_ORDER, data, JSONObject.toJSONString(vo));
            return ResponseDTO.success(true, "数据缓存成功！");
        } catch (Exception ex) {
            logger.error("数据缓存失败,vo:{},ex:{}", vo, ex.getMessage(), ex);
            return ResponseDTO.fail(ex.getMessage());
        }
    }

    /**
     * 通过平台、公司和城市ID检查配置信息是否已存在
     *
     * @param plat      平台ID
     * @param companyId 公司ID
     * @param cityId    城市ID
     * @param bizType
     * @return 是否存在配置信息
     */
    private Boolean checkExistsByCompanyAndCityId(Integer plat, Integer companyId, Integer cityId, Integer bizType) {

        DistributeWeightCompanyQuery query = new DistributeWeightCompanyQuery();
        query.setPlat(plat);
        query.setCompanyId(companyId);
        query.setCityId(cityId);
        query.setBizType(bizType);
        int count = distributeWeightCompanyService.countByQuery(query);
        return count > 0;
    }

    private Boolean checkExistsByCityId(Integer cityId, Integer plat, Integer distributeWay,Integer companyId,Integer bizType) {

        RobOrderConfigInfoQuery query = new RobOrderConfigInfoQuery();
        query.setCityId(cityId);
        query.setDistributeWay(distributeWay);
        query.setPlat(plat);
        query.setCompanyId(companyId);
        query.setBizType(bizType);
        int count = robOrderConfigBService.countByQuery(query);
        return count > 0;
    }

}
